package com.neteast.bustruck.utils

import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

/**
 * Gson
 *
 * @author Sunhy
 * Create time: 2024/3/20
 */
internal object GsonUtils {

    private val gson by lazy {
        GsonBuilder()
            .serializeNulls()
            .disableHtmlEscaping()
            .create()
    }

    fun toJson(obj: Any): String = gson.toJson(obj)

    fun <T> fromJson(
        json: String?,
        typeOfT: Type?,
    ): T? {
            try {
                return gson.fromJson(json, typeOfT)
            } catch (e: Exception) {

            }
        return null
    }

    /**
     * 获取 List Type
     * @param type Bean.class
     * @return List<Bean> Type
     */
    fun getListType(type: Type?): Type? {
        return TypeToken.getParameterized(List::class.java, type).type
    }

    /**
     * 获取 Array Type
     * @param type Bean.class
     * @return Bean[] Type
     */
    fun getArrayType(type: Type?): Type? {
        return TypeToken.getArray(type).type
    }


}